<template>
  <div class="pay-page">
    <v-title :title="$route.meta.title" />
    <loading :show="loading" />
    <ul class="list">
      <li class="id">
        <label>会员ID:</label>
        <span>{{ userId }}</span>
      </li>
      <li class="total">
        <label>支付金额:</label>
        <span>￥{{ +total }}</span>
      </li>
      <li class="submit">
        <span>{{ tips }}</span>
      </li>
    </ul>
  </div>
</template>

<script>
import Title from '@/components/Title'
import Loading from '@/components/Loading'
import base64 from '@/util/base64'
import api from '@/api'
import { isWxBrowser } from '@/util/wx'
export default {
  /*
    url: /pay/:serial
   */
  name: 'Pay',
  components: {
    'v-title': Title,
    Loading
  },
  data() {
    return {
      loading: false,
      // debug: wx ios browser
      replace: '&replace=1',
      tips: '正在支付中,请稍等 ...',
      url: window.location.href,
      userId: 0,
      total: 0,
      isThird: false
    }
  },
  methods: {
    calcPayTotal() {
      try {
        // parse serial
        let serial = this.$route.params.serial
        serial = serial.replace(this.replace, '')
        serial = base64.parse(serial)
        // select pay mode
        if (serial && serial.user_refill_id) {
          // refill
          this.loading = true
          api.Account.getRefillAmount({
            user_refill_id: serial.user_refill_id
          }).then(response => {
            let { data } = response
            data = base64.parse(data)
            this.total = data.amount
            this.payRefill(data)
          }).finally(() => {
            this.loading = false
          })
        } else if (serial && serial.order_id) {
          // order pay
          this.loading = true
          api.Order.getPayAmount({
            order_id: serial.order_id
          }).then(response => {
            let { data } = response
            data = base64.parse(data)
            this.total = data.amount
            this.isThird = data.third_pay
            if (!this.isThird) {
              this.payOrder(data)
            } else {
              this.payOrderThird(data)
            }
            // console.log(data)
          }).finally(() => {
            this.loading = false
          })
        } else if (serial && serial.merchant_order_id) {
          // merchant pay
          this.loading = true
          api.Merchant.getPayAmount({
            merchant_order_id: serial.merchant_order_id
          }).then(response => {
            let { data } = response
            data = base64.parse(data)
            this.total = data.amount
            this.payMerchant(data)
          }).finally(() => {
            this.loading = false
          })
        }
      } catch (e) {
        this.$createToast({
          type: 'error',
          txt: '操作错误',
          time: 1000,
          onTimeout: () => {
            this.$router.push('/')
          }
        }).show()
      }
    },
    payRefill(model) {
      // const domain = process.env.VUE_APP_BASE_API
      const domain = window.location.origin
      // openid redirect params
      const redirect = base64.encode(this.$route.path)
      api.Wx.getOpenid({
        user_id: model.user_id,
        redirect_url: domain + '/user/openid/' + redirect,
        // user_info: true,
        // debug: true
      }).then(response => {
        const { data } = response
        if (!data.openid && process.env.NODE_ENV !== 'dev') {
          window.location = data.url
        }
        this.loading = true
        api.Wx.jsApiPay_Wx({
          openid: data.openid,
          sn: model.sn,
          amount: model.amount,
          body: '充值',
          signature_url: this.url,
          pay_type: 2,
          pay_type_text: '充值',
          user_id: model.user_id
        }).then(() => {
          this.loading = false
          this.$createToast({
            type: 'correct',
            txt: '充值成功',
            time: 1000,
            onTimeout: () => {
              this.$router.push('/center')
            }
          }).show()
        }).catch(() => {
          this.loading = false
          this.$createToast({
            type: 'error',
            txt: '支付失败',
            time: 1000,
            onTimeout: () => {
              this.$router.push('/')
            }
          }).show()
        })
      })
    },
    payOrder(model) {
      // const domain = process.env.VUE_APP_BASE_API
      const domain = window.location.origin
      // openid redirect params
      const redirect = base64.encode(this.$route.path)
      api.Wx.getOpenid({
        user_id: model.user_id,
        redirect_url: domain + '/user/openid/' + redirect,
        // user_info: true,
        // debug: true
      }).then(response => {
        const { data } = response
        if (!data.openid && process.env.NODE_ENV !== 'dev') {
          window.location = data.url
        }
        this.loading = true
        api.Wx.jsApiPay_Wx({
          openid: data.openid,
          sn: model.sn,
          amount: model.amount,
          body: '购买商品',
          signature_url: this.url,
          pay_type: 1,
          pay_type_text: '订单',
          user_id: model.user_id
        }).then(() => {
          this.loading = false
          this.$createToast({
            type: 'correct',
            txt: '支付成功',
            time: 1000,
            onTimeout: () => {
              this.$router.push('/service/order/3')
            }
          }).show()
        }).catch(() => {
          this.loading = false
          this.$createToast({
            type: 'error',
            txt: '支付失败',
            time: 1000,
            onTimeout: () => {
              // this.$router.push('/')
            }
          }).show()
        })
      })
    },
    payOrderThird(model) {
      // const domain = process.env.VUE_APP_BASE_API
      const domain = window.location.origin
      // openid redirect params
      const redirect = base64.encode(this.$route.path)
      api.Wx.getOpenid({
        user_id: model.user_id,
        redirect_url: domain + '/user/openid/' + redirect,
        // user_info: true,
        // debug: true
      }).then(response => {
        const { data } = response
        if (!data.openid && process.env.NODE_ENV !== 'dev') {
          window.location = data.url
        }
        this.loading = true
        api.Wx.jsApiPay({
          openid: data.openid,
          sn: model.sn,
          amount: model.amount,
          body: '购买商品',
          signature_url: this.url,
          pay_type: 1,
          pay_type_text: '订单',
          user_id: model.user_id
        }).then(() => {
          this.loading = false
          this.$createToast({
            type: 'correct',
            txt: '支付成功',
            time: 1000,
            onTimeout: () => {
              this.$router.push('/service/order/3')
            }
          }).show()
        }).catch(() => {
          this.loading = false
          this.$createToast({
            type: 'error',
            txt: '支付失败',
            time: 1000,
            onTimeout: () => {
              this.$router.push('/')
            }
          }).show()
        })
      })
    },
    // payOrder(model) {
    //   api.Wx.jsApiPay_Wx_H5({
    //     // openid: data.openid,
    //     sn: model.sn,
    //     amount: model.amount,
    //     body: '购买商品',
    //     signature_url: this.url,
    //     pay_type: 1,
    //     pay_type_text: '订单',
    //     user_id: model.user_id
    //   }).then(() => {
    //     this.loading = false
    //     this.$createToast({
    //       type: 'correct',
    //       txt: '支付成功',
    //       time: 1000,
    //       onTimeout: () => {
    //         this.$router.push('/service/order/3')
    //       }
    //     }).show()
    //   }).catch(() => {
    //     this.loading = false
    //     this.$createToast({
    //       type: 'error',
    //       txt: '支付失败',
    //       time: 1000,
    //       onTimeout: () => {
    //         // this.$router.push('/')
    //       }
    //     }).show()
    //   })
    //   // const domain = window.location.origin
    //   // const redirect = base64.encode(this.$route.path)
    //   // api.Wx.getOpenid({
    //   //   user_id: model.user_id,
    //   //   redirect_url: domain + '/user/openid/' + redirect,
    //   // }).then(response => {
    //   //   const { data } = response
    //   //   if (!data.openid && process.env.NODE_ENV !== 'dev') {
    //   //     window.location = data.url
    //   //   }
    //   //   this.loading = true
    //   // })
    // },
    payMerchant(model) {
      // const domain = process.env.VUE_APP_BASE_API
      const domain = window.location.origin
      // openid redirect params
      const redirect = base64.encode(this.$route.path)
      api.Wx.getOpenid({
        user_id: model.user_id,
        redirect_url: domain + '/user/openid/' + redirect,
        // user_info: true,
        // debug: true
      }).then(response => {
        const { data } = response
        if (!data.openid && process.env.NODE_ENV !== 'dev') {
          window.location = data.url
        }
        this.loading = true
        api.Wx.jsApiPay({
          openid: data.openid,
          sn: model.sn,
          amount: model.amount,
          body: '购买商品',
          signature_url: this.url,
          pay_type: 1,
          pay_type_text: '订单',
          user_id: model.user_id
        }).then(() => {
          this.loading = false
          this.$createToast({
            type: 'correct',
            txt: '支付成功',
            time: 1000,
            onTimeout: () => {
              this.$router.push('/service/order/3')
            }
          }).show()
        }).catch(() => {
          this.loading = false
          this.$createToast({
            type: 'error',
            txt: '支付失败',
            time: 1000,
            onTimeout: () => {
              this.$router.push('/')
            }
          }).show()
        })
      })
    }
  },
  created () {
    if (!isWxBrowser()) {
      if (process.env.NODE_ENV !== 'dev') {
        return this.$createToast({
          type: 'warn',
          txt: '请在微信中打开',
          time: 1000
        }).show()
      }
    }
    // user info
    const info = this.$store.getters['ExecUser/info']
    if (info && info.id) {
      this.userId = info.id
    }
    this.url = process.env.VUE_APP_BASE_API + this.$route.fullPath
    this.calcPayTotal()
  },
  mounted () {
    // debug: wx ios browser
    const href = window.location.href
    const replace = this.replace
    if (href.indexOf(replace) <= -1) {
      window.location.replace(href + replace)
    }
  }
}
</script>

<style scoped lang="stylus">
.pay-page
  padding-top 45px
  .list
    background white
    margin 15px
    padding 20px
    border-radius 10px
    li
      height 35px
      line-height 35px
      &.id, &.total
        display flex
        label, span
          flex 1
        label
          text-align right
          padding-right 5px
        span
          text-align left
          padding-left 5px
          color red
          font-size 16px
      &.submit
        padding-top 10px
        span
          display inline-block
          background #ccc
          padding 0 30px
          border-radius 15px
          color white
          font-weight 700
</style>
